package com.lagou.handler;

import com.lagou.entity.RpcRequest;
import com.lagou.entity.RpcResponse;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.BeanUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RpcRequest request = (RpcRequest) msg;
        Class<?> aClass = Class.forName(request.getClassName());
        Method method = aClass.getMethod(request.getMethodName(), request.getParameterTypes());
        System.out.println("本次请求ID:" + request.getRequestId() + ",参数：" + request.getParameters());

        //获取bean
        Object bean = BeanUtil.getBean(aClass);
        RpcResponse result = (RpcResponse) method.invoke(bean, request.getParameters());
        result.setId(request.getRequestId());
        ctx.writeAndFlush(result);
    }
}
